package com.boge.whitelist;

import com.alibaba.fastjson.JSON;
import com.boge.ratelimiter.annotation.DoRateLimiter;
import com.boge.ratelimiter.valve.IValveService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

@Aspect
@Slf4j
public class DoRateLimiterPoint {

    @Autowired
    private IValveService valveService;

    @Pointcut("@annotation(com.boge.ratelimiter.annotation.DoRateLimiter)")
    public void aopPoint() {
    }

    @Around("aopPoint() && @annotation(doRateLimiter)")
    public Object doRouter(ProceedingJoinPoint jp,DoRateLimiter doRateLimiter) throws Throwable {
        Method method = getMethod(jp);
        return valveService.access(jp,method, doRateLimiter,jp.getArgs());
    }

    private Method getMethod(JoinPoint jp) throws NoSuchMethodException {
        Signature sig = jp.getSignature();
        MethodSignature methodSignature = (MethodSignature) sig;
        return jp.getTarget().getClass().getMethod(methodSignature.getName(), methodSignature.getParameterTypes());
    }

}

  